package com.kynnn.cloud.attribute_converter.handler;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

/**
 * @author Zhudiwei
 * @Description TODO
 * @createTime 2021年05月24日
 */
@MappedJdbcTypes(JdbcType.LONGVARCHAR)
@MappedTypes({List.class})
public class ListTypeHandler implements TypeHandler<List<String>> {

    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, List<String> list, JdbcType jdbcType) throws SQLException {
        String ids = StringUtils.join(list, ",");
        preparedStatement.setString(i, ids);
    }

    @Override
    public List<String> getResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        String ids = callableStatement.getString(columnIndex);
        return Arrays.asList(ids.split(","));
    }

    @Override
    public List<String> getResult(ResultSet resultSet, int columnIndex) throws SQLException {
        return Arrays.asList(resultSet.getString(columnIndex).split(","));
    }

    @Override
    public List<String> getResult(ResultSet resultSet, String columnName) throws SQLException {
        return Arrays.asList(resultSet.getString(columnName).split(","));
    }

}
